#!/bin/bash

# 创建 /web/html 目录
echo "创建 /web/html 目录..."
mkdir -p /web/html
chown -R www-data:www-data /web/html
chmod -R 755 /web/html

# 更新系统包
echo "更新系统包..."
apt-get update
apt-get upgrade -y

# 安装Web服务器（Nginx）
echo "安装Nginx..."
apt-get install nginx -y

# 安装PHP和必要的PHP扩展
echo "安装PHP和必要的扩展..."
apt-get install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-xmlrpc php-zip -y

# 安装MySQL数据库
echo "安装MySQL数据库..."
apt-get install mysql-server -y

# 配置MySQL
echo "配置MySQL..."
ROOT_PASS=$(openssl rand -base64 12 | tr -d '/+=' | cut -c1-16)
mysql_secure_installation <<EOF
y
${ROOT_PASS}
${ROOT_PASS}
y
y
y
y
EOF

# 随机生成数据库名、用户名和密码
echo "随机生成数据库名、用户名和密码..."
dbname="filebox_$(openssl rand -hex 3)"
dbuser="user_$(openssl rand -hex 3)"
dbpass=$(openssl rand -base64 12 | tr -d '/+=' | cut -c1-16)

# 创建数据库和用户
echo "创建数据库和用户..."
mysql -u root -p"${ROOT_PASS}" -e "CREATE DATABASE ${dbname};"
mysql -u root -p"${ROOT_PASS}" -e "CREATE USER '${dbuser}'@'localhost' IDENTIFIED BY '${dbpass}';"
mysql -u root -p"${ROOT_PASS}" -e "GRANT ALL PRIVILEGES ON ${dbname}.* TO '${dbuser}'@'localhost';"
mysql -u root -p"${ROOT_PASS}" -e "FLUSH PRIVILEGES;"

# 下载文件快递柜源码
echo "下载源码..."
wget -O /web/html/filebox.zip https://gitee.com/zxc72/service-code/raw/master/ruknbs.zip

# 安装unzip工具
echo "安装unzip工具..."
apt-get install unzip -y

# 解压zip文件到指定目录
echo "解压zip文件..."
unzip /web/html/ruknbs.zip -d /web/html/

# 设置文件权限
echo "设置文件权限..."
chown -R www-data:www-data /web/html
chmod -R 755 /web/html

# 配置Nginx
echo "配置Nginx..."
cat > /etc/nginx/sites-available/filebox <<EOF
server {
    listen 80;
    listen [::]:80;
    listen 5637;
    listen [::]:5637;
    server_name _;
    root /web/html;
    index index.php index.html index.htm;

    location / {
        try_files \$uri \$uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF

ln -s /etc/nginx/sites-available/filebox /etc/nginx/sites-enabled/
rm /etc/nginx/sites-enabled/default

# 重启Nginx
echo "重启Nginx..."
systemctl restart nginx

# 自动配置SSL
echo "自动配置SSL..."
read -p "请输入您的域名或IP地址（例如 example.com 或 192.168.1.1）：" domain_or_ip

# 安装Certbot以获取SSL证书
echo "安装Certbot..."
apt-get install certbot python3-certbot-nginx -y

# 获取SSL证书
echo "获取SSL证书..."
if [[ $domain_or_ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    # 如果是IP地址，使用自签名证书
    echo "检测到输入的是IP地址，使用自签名证书..."
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout /etc/ssl/private/nginx-selfsigned.key \
        -out /etc/ssl/certs/nginx-selfsigned.crt \
        -subj "/CN=${domain_or_ip}"

    # 配置Nginx使用自签名证书
    cat > /etc/nginx/sites-available/filebox <<EOF
server {
    listen 80;
    listen [::]:80;
    listen 5637;
    listen [::]:5637;
    server_name ${domain_or_ip};

    # 重定向所有HTTP请求到HTTPS
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name ${domain_or_ip};

    # 自签名证书路径
    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;

    # SSL配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    root /web/html;
    index index.php index.html index.htm;

    location / {
        try_files \$uri \$uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF
else
    # 如果是域名，使用Let's Encrypt证书
    echo "检测到输入的是域名，使用Let's Encrypt证书..."
    certbot --nginx -d ${domain_or_ip} -d www.${domain_or_ip} --non-interactive --agree-tos -m admin@${domain_or_ip}
fi

# 重启Nginx
echo "重启Nginx..."
systemctl restart nginx

# 下载证书检查脚本
echo "下载证书检查脚本..."
wget -O /usr/local/bin/check_certificates.sh https://gitee.com/zxc72/service-code/raw/master/check_certificates.sh
chmod +x /usr/local/bin/check_certificates.sh

# 配置计划任务
echo "配置计划任务..."
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/check_certificates.sh") | crontab -

# 安装并配置FTP服务
echo "安装并配置FTP服务..."
apt-get install vsftpd -y

# 随机生成FTP用户名和密码
echo "随机生成FTP用户名和密码..."
ftp_user="ftpuser_$(openssl rand -hex 3)"
ftp_pass=$(openssl rand -base64 12 | tr -d '/+=' | cut -c1-16)

# 创建FTP用户
echo "创建FTP用户..."
useradd -m -d /web/html -s /usr/sbin/nologin ${ftp_user}
echo "${ftp_user}:${ftp_pass}" | chpasswd
chown -R ${ftp_user}:${ftp_user} /web/html

# 配置vsftpd
echo "配置vsftpd..."
cat > /etc/vsftpd.conf <<EOF
listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
chroot_local_user=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO
local_root=/web/html
EOF

# 重启vsftpd服务
echo "重启vsftpd服务..."
systemctl restart vsftpd
systemctl enable vsftpd

# 输出部署信息
echo "部署完成！"
echo "数据库名称: ${dbname}"
echo "数据库用户: ${dbuser}"
echo "数据库密码: ${dbpass}"
echo "FTP 用户名: ${ftp_user}"
echo "FTP 密码: ${ftp_pass}"
echo "请拍照或截屏记录信息，以免丢失"

# 提示备案信息
echo "提示：如果服务器部署在中国大陆，请确保已完成域名备案！"

# 访问测试提示
if [[ $domain_or_ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "请访问以下地址进行访问测试："
    echo "HTTP: http://${domain_or_ip}:5637"
    echo "HTTPS: https://${domain_or_ip}"
else
    echo "请访问以下地址进行访问测试："
    echo "HTTP: http://${domain_or_ip}:5637"
    echo "HTTPS: https://${domain_or_ip}"
fi